<script setup lang="ts">
import { ref, onMounted, computed, nextTick, watch } from 'vue'
import { getImgSignedUrl } from '#/utils/getImgUrl'
import { getCertificationInfoByIdApi } from '#/api/lesson/pay'
import { useRoute } from 'vue-router'
import { getCertificateType } from '#/views/certificate/modules/const'

defineOptions({ name: 'SubmitOrder' })
const emit = defineEmits(['isSubmitOrder'])
defineProps<{
  loading: boolean,
  visible: boolean
}>()
const route = useRoute()
const certificationId = ref(route.params.id as string)
// 添加缺失的 quantity 变量
const quantity = ref(1)
const imgUrl = ref('')
const certData = ref<any>({})
const loading = ref(false)
const descriptionElement = ref<HTMLElement>()

// 处理悬浮提示位置
const handleTooltip = (event: MouseEvent) => {
  const target = event.target as HTMLElement
  const tooltip = target.querySelector('.tooltip') as HTMLElement
  if (tooltip) {
    const rect = target.getBoundingClientRect()
    tooltip.style.left = rect.left + 'px'
    tooltip.style.top = (rect.bottom + 8) + 'px'
  }
}

// 检查文本是否被截断
const isTextTruncated = ref(false)

// 检查文本截断状态
const checkTextTruncation = () => {
  if (!descriptionElement.value) return
  const element = descriptionElement.value
  // 检查是否有省略号（通过比较scrollHeight和clientHeight）
  const isTruncated = element.scrollHeight > element.clientHeight
  isTextTruncated.value = isTruncated
}

// 封装一个方法判断有值还是没有值
function hasValue(val: string | number | undefined | null): boolean {
  // '' 字符串空值表示没有值，0表示有值，NaN表示没有值
  if (val === '' || Number.isNaN(val)) return false;
  return val !== undefined && val !== null;
}

const price = computed(() => {
  const targetPrice = certData.value.targetPrice
  const discountPrice = certData.value.discountPrice
  if (hasValue(discountPrice)) {
    return Number(discountPrice).toFixed(2)
  }
  if (hasValue(targetPrice) && !hasValue(discountPrice)) {
    return Number(targetPrice).toFixed(2)
  }
  return '0.00'
})

onMounted(async () => {
  // if (props.loading) return
  const res = await getCertificationInfoByIdApi(certificationId.value)
  const { certificateImage, name, description, type, targetPrice, discountPrice } = res
  certData.value = {
    certificateImage,
    name,
    description,
    type,
    targetPrice,
    discountPrice
  }
  if (!hasValue(targetPrice) && !hasValue(discountPrice)) {
    emit('isSubmitOrder', true)
  }
  if (!certificateImage) return
  loading.value = true;
  getImgSignedUrl(certificateImage).then(res => {
    imgUrl.value = res as string
  }).finally(() => {
    loading.value = false
  })
  
  // 等待DOM更新后检查文本截断状态
  await nextTick()
  checkTextTruncation()
})

// 监听描述文本变化，重新检查截断状态
watch(() => certData.value.description, async () => {
  await nextTick()
  checkTextTruncation()
})

defineExpose({
  getPrice: () => price.value,
  getQuantity: () => quantity.value
})

</script>

<template>
  <div class="submit-order-container">
    <!-- 上方：图片和标题描述 -->
    <div class="flex items-start gap-6 h-[112px]">
      <!-- 左侧图片 -->
      <div class="w-[200px] h-[112px] flex items-center justify-center rounded border" v-loading="loading">
        <img :src="imgUrl" alt="证书图片" class=" h-full object-cover object-contain" />
      </div>
      <!-- 右侧内容 -->
      <div class="flex-1 flex flex-col justify-between min-h-[112px] pt-4">
        <h2 class="text-[20px] font-[500]">{{ certData.name }}</h2>
        <p class="text-sm break-words line-clamp-2
          text-[#595959] description-text" @mouseenter="handleTooltip" @mousemove="handleTooltip"
          ref="descriptionElement">
          {{ certData.description }}
        <div class="tooltip" v-if="certData.description && isTextTruncated">{{ certData.description }}</div>
        </p>
      </div>
    </div>

    <!-- 下方：字段信息 -->
    <div class="space-y-4 pt-10">
      <!-- 服务项 -->
      <div class="field-row">
        <span class="field-label">服务项</span>
        <span class="field-tag">{{ certData.name }}</span>
      </div>

      <!-- 认证类型 -->
      <div class="field-row">
        <span class="field-label">认证类型</span>
        <span class="field-tag">{{ getCertificateType(certData.type) }}</span>
      </div>
      <!-- 购买方式 -->
      <div class="field-row">
        <span class="field-label">购买方式</span>
        <span class="field-tag">按次</span>
      </div>
      <!-- 购买数量和合计在同一行 -->
      <div class="flex items-center justify-between">
        <!-- 左侧：购买数量 -->
        <div class="flex items-center">
          <span class="field-label">购买数量</span>
          <el-input type="number" min="1" max="99" :disabled="true" v-model="quantity" class="quantity-input" />
        </div>
        <!-- 右侧：合计 -->
        <div class="flex items-center">
          <span class="mr-4 text-lg">合计</span>
          <span class="text-3xl font-[500] text-[#e5484d]">{{ price }}</span>
          <span class="text-[#e5484d] text-lg ml-1">元</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 公共样式 */
.field-row {
  @apply flex items-center;
}

.field-label {
  @apply text-[#595959] w-16 text-right mr-4;
}

.field-tag {
  @apply bg-[#0067d129] text-[--el-color-primary] px-3 py-2 rounded min-w-20 text-center;
}

.quantity-input {
  width: 80px;
}

.quantity-input :deep(.el-input__inner) {
  @apply text-center;
}

/* 图片容器样式 */
.image-container {
  @apply relative overflow-hidden;
}

/* 描述文本悬浮提示样式 */
.description-text {
  position: relative;
}

.tooltip {
  position: fixed;
  background: white;
  /* color: white; */
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
  z-index: 9999;
  max-width: 740px;
  word-wrap: break-word;
  white-space: normal;
  pointer-events: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  display: none;
}

.description-text:hover .tooltip {
  display: block;
}

</style>
